#include "ch32x035.h"
#include "stdint.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "cpuusage.h"

#include "DevicesDelay.h"
#include "DevicesADC.h"
#include "DevicesLed.h"
#include "DevicesPWM.h"
#include "DevicesQueue.h"
#include "DevicesSPI.h"
#include "DevicesTimer.h"
#include "DevicesUart.h"
#include "DevicesWatchDog.h"
#include "DevicesTime.h"
#include "DevicesWatchDog.h"
#include "DevicesUID.h"
#include "DevicesCi24R1.h"

#include "DriverDCDC.h"

#include "microConfig.h"
#include "taskTimer.h"
#include "taskPD.h"
#include "taskSystem.h"


/* 系统初始化任务句柄 */
MrTaskType *g_TaskSystemInitHand = NULL;

/* 消息队列句柄 */
MrMessageType *g_ptypeMrMessageNetwork = NULL;

uint8_t st_ucMessageBuff[128];



void vApplicationIdleHook(void)
{
    /* CPU占用率计算 */
    vCPUUsageIdleHook();

    /* 喂狗 */
    vWatchdogReload();
}


void vUserSystemInit(void)
{
    enumQueueInit();

    vLedInit();

    vWatchdogInit();
}

void vTaskSystemInit(uint32_t uiParameters)
{
    int32_t iLength;

    printf("MicroRTOS start succeed...\r\n");

    vUserSystemInit();
    printf("SystemInit succeed.\r\n");


    /* 创建1个软件定时器 */
    cMrTimerCreate(&g_ptypeMrTimerPrintf, vMrTimerPrintf, 0, 1000);
    /* 启动定时器 */
    cMrTimerStart(g_ptypeMrTimerPrintf, MrTimerCirculation, g_ptypeMrTimerPrintf->duration);


    /* 创建消息队列 */
    cMrMessageCreate(&g_ptypeMrMessageNetwork, MR_MESSAGE_TYPE_FIFO, sizeof(uint32_t), 1, 0);


    /* 创建 PD 任务 */
    cMrTaskCreate(&g_TaskPDHand, vTaskPD, "PD", 1, 2048, 0);


    while(1)
    {
        /* 永久等待，直到接收到消息 */
        cMrMessageSemaphoreRead(g_ptypeMrMessageNetwork, -1);

        /* 读取并解析 上位机 发送过来的数据 */
        while((iLength = iQueueGetLength(&g_TypeQueueUart2Read)) > 0)
        {
            iLength = (iLength > sizeof(st_ucMessageBuff)) ? sizeof(st_ucMessageBuff) : iLength;

            enumQueuePopDatas(&g_TypeQueueUart2Read, st_ucMessageBuff, iLength);

            vUartDMASendDatas(USART2, st_ucMessageBuff, iLength);
        }
    }
}
